import { registerAs } from '@nestjs/config'
import { DocumentBuilder } from '@nestjs/swagger'
import { createHash } from 'crypto'
import { extname, resolve } from 'path'
import { diskStorage } from 'multer'
import makeDir from 'make-dir'
import { IConfig } from '@/common/interfaces'
import { loggerOptions } from './logger.options'

export default registerAs(
  '',
  (): IConfig => ({
    port: 3000,
    prefix: '/api',
    static: {
      path: resolve('static')
    },
    winston: loggerOptions,
    multer: {
      storage: diskStorage({
        destination: (req, file, cb) => {
          const dir = makeDir.sync('static/uploads')

          cb(null, dir)
        },
        filename: (req, file, cb) => {
          const fileName = createHash('sha256')
            .update(file.originalname + Date.now())
            .digest('hex')
          const extName = extname(file.originalname)

          cb(null, `${fileName}${extName}`)
        }
      })
    },
    casbin: {
      modelPath: resolve('./model.conf'),
      adapterOptions: {
        type: 'mysql',
        host: '127.0.0.1',
        port: 3306,
        username: 'root',
        password: 'root',
        database: 'test_for_node'
      }
    },
    typeorm: {
      type: 'mysql',
      host: '127.0.0.1',
      port: 3306,
      username: 'root',
      password: 'root',
      database: 'test_for_node',
      entities: ['src/**/*.entity.ts'],
      retryAttempts: 5,
      retryDelay: 1500,
      subscribers: ['src/**/*.subscriber.ts'],
      synchronize: true
    },
    passport: {
      defaultStrategy: 'jwt'
    },
    jwt: {
      secret: 'secret',
      signOptions: {
        expiresIn: 3600
      }
    },
    swagger: {
      path: '/swagger',
      statsPath: '/swagger-stats',
      config: new DocumentBuilder()
        .setTitle('Nest Template')
        .setVersion('1.0.0')
        .setLicense('MulanPSL2', 'http://license.coscl.org.cn/MulanPSL2')
        .addBearerAuth({
          type: 'apiKey',
          name: 'Authorization',
          in: 'header'
        })
        .build()
    }
  })
)
